package com.example.demo.controller;

import com.alibaba.fastjson.JSON;
import com.example.demo.bean.Expense;
import com.example.demo.bean.Medicine;
import com.example.demo.bean.QueryInfo;
import com.example.demo.dao.ExpenseDao;
import com.example.demo.dao.MedicineDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
public class ExpenseController {
    @Autowired
    ExpenseDao expenseDao;
    @Autowired
    MedicineDao medicineDao;

    //获取所有的采购信息
    @RequestMapping("/getAllExpense")
    public String getAllExpense(){
        List<Expense> expenses = expenseDao.getAllExpense();
        List<Medicine> medicines = new ArrayList<>(expenses.size());
        Set<String> processedMedicineIds = new HashSet<>(); // 用来记录已处理过的药品ID，避免重复查询

        for (Expense expense : expenses) {
            String medicineId = expense.getMedicineID();
            // 如果该药品ID还未被查询过，则进行查询并添加到结果列表
            if (!processedMedicineIds.contains(medicineId)) {
                List<Medicine> foundMedicines = expenseDao.findMedicine(medicineId);
                if (foundMedicines != null && !foundMedicines.isEmpty()) {
                    medicines.addAll(foundMedicines); // 添加查询到的药品信息到结果列表
                    processedMedicineIds.add(medicineId); // 记录已处理的药品ID
                }
            }
        }
        HashMap<String, Object> res = new HashMap();
        //错误-404；成功-200
        int status = 200;
        res.put("code",status);
        res.put("expenses",expenses);
        res.put("medicines",medicines);
        String s = JSON.toJSONString(res);
        return s;
    }

    //增加|修改采购信息
    @PostMapping("/addExpense")
    public Integer addExpense(@RequestBody Expense expense){
        //把请求体的药品数据给medicine
        Medicine medicine=expense.getMedicine();
//        id不为0就是修改
        if(expense.getId()!=0){
            int num3=expenseDao.editExpense(expense);
            int num4=medicineDao.editMedicine(medicine);
            System.out.println(medicine);
            //当两个都成功，则返回1
            if(num3!=0 && num4!=0){
                return 1;
            }else
                return 0;
        }else{
            int num1=expenseDao.addExpense(expense);
            int num2=medicineDao.addMedicine(medicine);
            //当两个都成功，则返回1
            if(num1!=0 && num2!=0){
                return 1;
            }else
                return 0;
        }
    }

    //删除采购信息
    @DeleteMapping("/deleteExpense/{id}")
    public Integer deleteExpense(@PathVariable int id){
        Integer res=expenseDao.deleteExpense(id);
        if(res==1){
            return 1;
        }else{
            return 0;
        }
    }
}
